/**
 * Created by lupf on 2016/4/28.
 */

angular.module('myApp')

    .controller('queryCtrl',['$scope', '$http', '$httpParamSerializerJQLike', '$log', 'OpenService', 'CheckboxService',
        'CacheService', 'limitToFilter', 'filterFilter','myConstant', function ($scope, $http, $httpParamSerializerJQLike, $log, OpenService, CheckboxService,
                                       CacheService, limitToFilter, filterFilter,myConstant) {
        //视图层变量viewModel
        var vm = $scope.vm = {};
        vm.constant = myConstant;
        //变量初始化
        //分页数据
        vm.pagination = {
            pageSize: 10,
            pageNum: 1
        };
        //查询条件
        vm.queryBean = {};

        //缓存数据初始化(需要缓存的key请自定义)
        /*数据格式{
         key1 :value1,
         key2:value2
         }*/
        vm.cached = {

            MERCHANT_CODE: {},
            SPECIALLY_AUDIT_STATUS: {},


        };

            CacheService.initCache(vm.cached);

        /*将前面缓存的数据格式化
         [{key:value},{key:value}]*/
        vm.getCache = function (key) {
            return CacheService.getCache(key);
        };

        //获取对象数据[user,user,user]
        vm.getObj = function (key, input) {
            return $http.post(config.ctx + '/base/cache/getAll',
                $httpParamSerializerJQLike({cacheKey: key}))
                .then(function (response) {
                    return limitToFilter(filterFilter(response.data.object, input), 6);
                }, function (response) {
                    $log.error('获取数据%s失败', cacheKey);
                })
        };
            vm.cache = {
                ADDRESS_Select:{},
                MERCHANT_PROPERTY: {},
                CUSTPROPERTY: {},
                RISK_EVENT_CHANNEL: {},
                INFORMATION_LEVEL: {},
                UPLOAD_MODE: {},
                MERCHANT_TYPE: {},
                PO_CREDENTIALS_TYPE: {},
                LEGAL_CREDENTIALS_TYPE: {},
                MERCHANT_RISK_TYPE: {}
            };

            //批量获取缓存
            var keys = [];
            for (var key in  vm.cache) {
                keys.push(key);
            }
            $log.debug('批量查询缓存');
            $http.post(config.ctx + '/specially/dataDic/cache/get', keys, config.jsonHeader)
                .then(function (response) {
                    var tempMap = response.data.object;
                    for (var key in vm.cache) {
                        if (!angular.isUndefined(tempMap[key])) {
                            vm.cache[key] = tempMap[key];
                        }
                    }
                }, function (response) {
                    $log.error('获取数据%s失败', keys);
                })


            vm.queryDetail = queryDetail;
        vm.resetForm = resetForm;

        /*------------------以上配置通用---------------------*/


        vm.addItem = addItem;
        vm.queryMerchantRiskDetail = queryMerchantRiskDetail;
        vm.deleteItem = deleteItem;

        /*------------------以上方法名可选择性通用---------------------*/


        function queryDetail() {
            var queryForm = document.getElementById('queryForm');
            vm.url = angular.element(queryForm).prop('action');

            //组织参数：查询条件 + 分页数据
            vm.postData = vm.queryBean;
            vm.postData.pageSize = vm.pagination.pageSize;
            vm.postData.pageNum = vm.pagination.pageNum;
            $http.post(vm.url, $httpParamSerializerJQLike(vm.postData))
                .then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        vm.pagination = data.object;
                        //清空选中记录
                        CheckboxService.clearChecked();
                    } else {
                        alert(data.msg);
                    }
                });

        };

        function resetForm() {
            vm.queryBean = {};
        }


        function addItem() {
            OpenService({
                modalTitle: '新增商户风险信息',
                modalBody: 'toAdd',
                url: 'add',
                cached: {
                    MERCHANT_PROPERTY: vm.cache.MERCHANT_PROPERTY,
                    INFORMATION_LEVEL: vm.cache.INFORMATION_LEVEL,
                    CUSTPROPERTY: vm.cache.CUSTPROPERTY,
                    RISK_EVENT_CHANNEL: vm.cache.RISK_EVENT_CHANNEL,
                    MERCHANT_TYPE: vm.cache.MERCHANT_TYPE,
                    LEGAL_CREDENTIALS_TYPE: vm.cache.LEGAL_CREDENTIALS_TYPE,
                    PO_CREDENTIALS_TYPE: vm.cache.PO_CREDENTIALS_TYPE,
                    UPLOAD_MODE: vm.cache.UPLOAD_MODE,
                    ADDRESS_Select:vm.cache.ADDRESS_Select,
                    MERCHANT_CODE: vm.getCache('MERCHANT_CODE'),
                    MERCHANT_CODE_MAP: vm.cached.MERCHANT_CODE,
                    MERCHANT_RISK_TYPE: vm.cache.MERCHANT_RISK_TYPE
                }
            }, function () {
            }, 'addMerchantRiskCtrl','myModalNoFooter.html');
        }
        function queryMerchantRiskDetail(bean) {
                var item=bean;
                OpenService({
                    modalTitle: '查看明细',
                    modalBody: 'toDetail',
                    url: '#',
                    item: item,
                    cached: {
                        MERCHANT_PROPERTY: vm.cache.MERCHANT_PROPERTY,
                        INFORMATION_LEVEL: vm.cache.INFORMATION_LEVEL,
                        MERCHANT_TYPE: vm.cache.MERCHANT_TYPE,
                        MERCHANT_CODE: vm.cached.MERCHANT_CODE,
                        LEGAL_CREDENTIALS_TYPE: vm.cache.LEGAL_CREDENTIALS_TYPE,
                        PO_CREDENTIALS_TYPE: vm.cache.PO_CREDENTIALS_TYPE,
                        RISK_EVENT_CHANNEL: vm.cache.RISK_EVENT_CHANNEL,
                        SPECIALLY_AUDIT_STATUS: vm.cached.SPECIALLY_AUDIT_STATUS,
                        UPLOAD_MODE: vm.cache.UPLOAD_MODE,
                        CUSTPROPERTY: vm.cache.CUSTPROPERTY,
                        MERCHANT_RISK_TYPE: vm.cache.MERCHANT_RISK_TYPE
                    }
                }, function (item) {
                }, '', 'myModalNoSave.html');
            }

            function deleteItem() {
                if (CheckboxService.getCheckedNew(vm.pagination.list).length != 1) {
                    alert("必须勾选一条记录！");
                    return;
                }
                $http.post('delete', $httpParamSerializerJQLike({'id': CheckboxService.getCheckedNew(vm.pagination.list)[0].id}))
                    .then(function (response) {
                        var data = response.data;
                        if (data.success) {
                            vm.pagination.list.splice(vm.pagination.list.indexOf(CheckboxService.getCheckedNew(vm.pagination.list)[0]), 1);
                            alert("操作成功");
                        } else {
                            alert("操作失败");
                        }
                    }, function (response) {
                        alert(response.statusText);
                        $log.debug("error");
                    });
            }
    }]);

angular.module('myApp').controller('addMerchantRiskCtrl',['$scope', '$uibModalInstance', 'modalItem', '$http',
    '$httpParamSerializerJQLike','FileUploader','dateFilter','$log','myConstant','DateCalculateService', function ($scope, $uibModalInstance, modalItem, $http,
                                                                                            $httpParamSerializerJQLike,FileUploader,dateFilter,$log,myConstant,DateCalculateService) {

        var vm = $scope.vm = {
            modalTitle: '新增商户风险信息',
            modalBody: '#',
            url: '',
            item: {}
        }

        function isNull(code){
            if (code =="" || code==undefined || code== null) {
                return true;
            }else{
                return false;
            }
        };

        vm = $scope.vm = modalItem;
        vm.constant = myConstant;
        vm.basicData=[{"areaCode":"","areaName":"","cityCode":"","cityName":""}];
        vm.addOccurarea = function addOccurarea(areaCode,areaName,cityCode,cityName) {
            if(vm.basicData.length>10){
                alert("风险事件发生地域不能超过10个！");
                return;
            }
            if(isNull(cityCode)){
                cityName=areaName;
            }
            if (isNull(areaCode)) {
                alert("请选择风险事件发生地域！");
                return;
            }else{
                if(vm.basicData.length>1){
                    for(var i=0;i<vm.basicData.length;i++){
                        if(vm.basicData[i].cityCode==cityCode && !isNull(cityCode)){
                            alert("已添加过该地域,请重新添加！");
                            return;
                        }
                        if(!isNull(areaCode) && isNull(cityCode) && isNull(vm.basicData[i].cityCode) && vm.basicData[i].areaCode==areaCode){
                            alert("已添加过该地域,请重新添加！");
                            return;
                        }
                    }
                }
                vm.basicData.push({"areaCode": areaCode, "areaName": areaName, "cityCode": cityCode, "cityName": cityName});
            }

        };


        vm.deleteOccurarea = function deleteOccurarea(index) {
           /* if (index == 0) {
                alert("第一条信息不能删除!");
            } else {*/
                vm.basicData.remove(index);
           // }
        };
        Array.prototype.remove = function (dx) {
            if (isNaN(dx) || dx > this.length) {
                return false;
            }
            for (var i = 0, n = 0; i < this.length; i++) {
                if (this[i] != this[dx]) {
                    this[n++] = this[i]
                }
            }
            this.length -= 1
        };
        $scope.save = function () {
            var postData = angular.copy(vm.item);
            var startD = postData.occurtimeb;
            var endD   = postData.occurtimee;
            var validay = postData.validDate;
            var today = DateCalculateService.getToday();
            var code="";
            postData.regName = vm.cached.MERCHANT_CODE_MAP[postData.cusCode];
            if(postData.regName==null||postData.regName==''||postData.regName==undefined){
                alert("该商户非本机构商户，请重新输入!");
                return false;
            }
            for(var i=1;i<vm.basicData.length;i++){
                var cityCode=vm.basicData[i].cityCode;
                if(vm.basicData[i].cityCode==""||vm.basicData[i].cityCode==null||vm.basicData[i].cityCode==undefined){
                    if(vm.basicData[i].areaCode!="" && vm.basicData[i].areaCode!=null && vm.basicData[i].areaCode!=undefined) {
                        code = code + vm.basicData[i].areaCode;
                    }
                }else{
                    code=code+cityCode;
                }
                code=code+",";
                postData.occurarea=code;
            }
            var cusType = postData.cusType;
            var docCode = postData.docCode;
            var docType = postData.docType;
            var cusCode = postData.cusCode;
            var legDocType = postData.legDocType;
            var legDocCode = postData.legDocCode;
            if(cusType!="01"){
                if(cusCode==""||cusCode==null||cusCode==undefined){
                    alert("商户类型为非自然人时，商户代码必填!");
                    return false;
                }
                if(docType==""||docType==null||docType==undefined){
                    alert("商户类型为非自然人时，法人证件类型必填!");
                    return false;
                }
                if(docCode==""||docCode==null||docCode==undefined){
                    alert("商户类型为非自然人时，法人证件号码必填!");
                    return false;
                }

            }
            if(legDocType=="01"){
                if(isIdCode(legDocCode)){
                    alert("法定代表人（负责人）证件号码格式有误，请重新输入!");
                    return false;
                }
            }
            function isIdCode(str){
                var reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
                if(reg.test(str)){
                    return false;
                }
                return true;
            }
            if(postData.occurarea==""||postData.occurarea==null||postData.occurarea==undefined){
                alert("风险事件发生区域不能为空!");
                return false;
            }
            if(startD > today){
                alert("发生时间不能大于今天!");
                return false;
            }
            if(endD < startD){
                alert("结束时间不能小于开始时间!");
                return false;
            }
            if(validay < today){
                alert("有效期不能小于今天!");
                return false;
            }
           $http.post(vm.url, postData,config.jsonHeader)
                .then(function (response) {
                    if (response.data.success) {
                        alert("操作成功");
                        $uibModalInstance.close(vm.item);
                    } else {
                        alert(response.data.msg);
                    }
                }, function (response) {
                    alert("操作失败");
                    alert(response.status);
                })
        }

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    }]);